//给定一个整数数组 nums 和一个目标值 target，请你在该数组中找出和为目标值的那 两个 整数，并返回他们的数组下标。
//给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]
let numsArr = [2, 7, 11, 15]

//解法1 双循环

function twoSum(nums,targets){
    let arrs  =[];
    for(let i=0,l=nums.length;i<l;i++){
        for(let j=1;j<l;j++){
            if(nums[i]+nums[j]==targets){
                arrs.push(i,j)
                return arrs
            }
        }
    }
}


console.log(twoSum(numsArr,9))

//解法2 比较map

function twoSum2(nums,target){
    let arrs = [];
    let maps = new Map();
    for(let i in nums){
        maps.set(
            nums[i],
            i
        );
    }
    console.log(maps,'map结构')
    for(let j=0,l=nums.length;j<l-1;j++){
        if(maps.has(target -nums[j]) && maps.get(target - nums[j])!=j){
            arrs.push(j,maps.get(target - nums[j]))
            return arrs
        }
    }
}

console.log(twoSum2(numsArr,13))

// 边存边比较
 function twoSum3(nums, target) {
    const map = {}
    for (let i = 0; i < nums.length; i++){
        if(map[target - nums[i] ] >= 0){
            return [ map[target - nums[i] ], i]
        }
        map[nums[i]] = i;            
       
     } 
 
 }

 console.log(twoSum3(numsArr,13))

 //尾递归
  function twoSum4(nums, target, i = 0, maps = {}) {
    const map = maps
        if(map[target - nums[i] ] >= 0 ) {
            return [ map[target - nums[i] ], i]
        } else {
            map[ nums[i] ] = i;
            i++;
            if(i < nums.length - 1){
                return twoSum(nums, target, i, map)
            }else {
                throw 'error: twoSum is not find'
            }
            
            
        }
}

console.log(twoSum4(numsArr,9))

//indexof
function twoSum5(nums, target) {
    let result = [];
    nums.map((item, index) => {
      if (nums.indexOf(target - item) > -1 && nums.indexOf(target - item) != index) {
        result = [index, nums.indexOf(target - item)].sort((a, b) => a > b);
      }
    });
    return result;
  };

  console.log(twoSum5(numsArr,13))

  //以上所有的只能取符合条件的最后一个 如果是取附符合条件的所有呢?